package com.example.smartvillage.cunmin;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;
import android.widget.Toast;

import androidx.appcompat.widget.AppCompatSeekBar;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.example.smartvillage.MainViewModel;
import com.example.smartvillage.R;
import com.example.smartvillage.onenet.MyOneNetApi;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.textview.MaterialTextView;
import com.google.gson.JsonArray;

public class AutoAdaptFragment extends BottomSheetDialogFragment {

    private static final String TAG = "自动调节";

    MainViewModel model;
    MyOneNetApi myOneNetApi;

    MaterialTextView tv_state,tv_light,tv_heat,tv_humid;
    MaterialButton btn_switch,btn_light,btn_heat,btn_humid;
    AppCompatSeekBar sb_light,sb_heat,sb_humid;

    public AutoAdaptFragment() { }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        model = new ViewModelProvider(requireActivity()).get(MainViewModel.class);
        myOneNetApi = model.getMyOneNetApi().getValue();
        model.getAutoAdaptModel();

        //每次进入更新数据
        boolean[] newStates = new boolean[4];
        int[] newValues = new int[3];
        String dataStreamId = "灯光4模式,灯光4调节,加热模式,加热调节,加湿模式,加湿调节,自动模式";
        myOneNetApi.getDataStreams(dataStreamId, response -> {
            if (response.body() != null && response.body().get("errno").getAsInt() == 0) {
                JsonArray obj = response.body().get("data").getAsJsonArray();
                newStates[0] = (obj.get(0).getAsJsonObject().get("current_value").getAsInt() == 1);
                newValues[0] = obj.get(1).getAsJsonObject().get("current_value").getAsInt();
                newStates[1] = (obj.get(2).getAsJsonObject().get("current_value").getAsInt() == 1);
                newValues[1] = obj.get(3).getAsJsonObject().get("current_value").getAsInt();
                newStates[2] = (obj.get(4).getAsJsonObject().get("current_value").getAsInt() == 1);
                newValues[2] = obj.get(5).getAsJsonObject().get("current_value").getAsInt();
                newStates[3] = (obj.get(6).getAsJsonObject().get("current_value").getAsInt() == 1);
                Log.d(TAG, "获取的自动调节状态："+newStates[3]+"，灯光4："+newStates[0]+newValues[0] +
                        "，加热："+newStates[1]+newValues[1]+"，加湿："+newStates[2]+newValues[2]);
                model.setAutoAdaptModel(new AutoAdaptModel(newStates, newValues));
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_auto_adapt, container, false);
        btn_switch = view.findViewById(R.id.auto_adapt_button);
        btn_switch.setOnClickListener(onClickListenerSwitch);
        btn_light = view.findViewById(R.id.auto_adapt_button_light);
        btn_light.setOnClickListener(onClickListenerLight);
        sb_light = view.findViewById(R.id.auto_adapt_slider_light);
        sb_light.setOnSeekBarChangeListener(onSeekBarChangeListenerLight);
        btn_heat = view.findViewById(R.id.auto_adapt_button_heat);
        btn_heat.setOnClickListener(onClickListenerHeat);
        sb_heat = view.findViewById(R.id.auto_adapt_slider_heat);
        sb_heat.setOnSeekBarChangeListener(onSeekBarChangeListenerHeat);
        btn_humid = view.findViewById(R.id.auto_adapt_button_humid);
        btn_humid.setOnClickListener(onClickListenerHumid);
        sb_humid = view.findViewById(R.id.auto_adapt_slider_humid);
        sb_humid.setOnSeekBarChangeListener(onSeekBarChangeListenerHumid);
        tv_state = view.findViewById(R.id.auto_adapt_state);
        tv_light = view.findViewById(R.id.auto_adapt_value_light);
        tv_heat = view.findViewById(R.id.auto_adapt_value_heat);
        tv_humid = view.findViewById(R.id.auto_adapt_value_humid);

        model.getAutoAdaptModel().observe(this, autoAdaptModelObserver);

        return view;
    }

    //全局开关
    View.OnClickListener onClickListenerSwitch = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AutoAdaptModel autoAdaptModel = model.getAutoAdaptModel().getValue();
            boolean[] states = autoAdaptModel.getStates();
            //当前状态为开，则关闭，否则开启
            String command = "aimode:"+(states[3]?"0":"1");

            //在线命令
            myOneNetApi.sendCommand(command, response -> {
                if (response.body() != null && response.body().get("errno").getAsInt() == 0) {
                    Toast.makeText(getContext(), "成功创建命令", Toast.LENGTH_SHORT).show();

                    //更新ViewModel中的数据
                    states[3] = !states[3];
                    autoAdaptModel.setState(states[3], 3);
                    model.setAutoAdaptModel(autoAdaptModel);
                }
                else if (response.body().get("errno").getAsInt() == 10) {
                    Toast.makeText(getContext(), "设备不在线", Toast.LENGTH_SHORT).show();
                }
            });
        }
    };

    //亮度
    View.OnClickListener onClickListenerLight = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AutoAdaptModel autoAdaptModel = model.getAutoAdaptModel().getValue();
            boolean[] states = autoAdaptModel.getStates();
            //当前状态为开，则关闭，否则开启
            String command = "LED42:"+(states[0]?"0":"1");

            //在线命令
            myOneNetApi.sendCommand(command, response -> {
                if (response.body() != null && response.body().get("errno").getAsInt() == 0) {
                    Toast.makeText(getContext(), "成功创建命令", Toast.LENGTH_SHORT).show();

                    //更新ViewModel中的数据
                    states[0] = !states[0];
                    autoAdaptModel.setState(states[0], 0);
                    model.setAutoAdaptModel(autoAdaptModel);
                }
                else if (response.body().get("errno").getAsInt() == 10) {
                    Toast.makeText(getContext(), "设备不在线", Toast.LENGTH_SHORT).show();
                }
            });
        }
    };
    SeekBar.OnSeekBarChangeListener onSeekBarChangeListenerLight = new SeekBar.OnSeekBarChangeListener() {
        int progress;
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            this.progress = progress;
            tv_light.setText(String.valueOf(progress));
            Log.d(TAG, "onProgressChanged: 进度：" + progress + "来自用户：" +fromUser);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            AutoAdaptModel autoAdaptModel = model.getAutoAdaptModel().getValue();
            //
            String command = "LED43:"+progress;

            //在线命令
            myOneNetApi.sendCommand(command, response -> {
                if (response.body() != null && response.body().get("errno").getAsInt() == 0) {
                    Toast.makeText(getContext(), "成功创建命令", Toast.LENGTH_SHORT).show();

                    autoAdaptModel.setValue(progress, 0);
                    //更新ViewModel中的数据
                    model.setAutoAdaptModel(autoAdaptModel);
                }
                else if (response.body().get("errno").getAsInt() == 10) {
                    Toast.makeText(getContext(), "设备不在线", Toast.LENGTH_SHORT).show();
                }
            });
        }
    };

    //温度
    View.OnClickListener onClickListenerHeat = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AutoAdaptModel autoAdaptModel = model.getAutoAdaptModel().getValue();
            boolean[] states = autoAdaptModel.getStates();
            //当前状态为开，则关闭，否则开启
            String command = "heat2:"+(states[1]?"0":"1");

            //在线命令
            myOneNetApi.sendCommand(command, response -> {
                if (response.body() != null && response.body().get("errno").getAsInt() == 0) {
                    Toast.makeText(getContext(), "成功创建命令", Toast.LENGTH_SHORT).show();

                    //更新ViewModel中的数据
                    states[1] = !states[1];
                    autoAdaptModel.setState(states[1], 1);
                    model.setAutoAdaptModel(autoAdaptModel);
                }
                else if (response.body().get("errno").getAsInt() == 10) {
                    Toast.makeText(getContext(), "设备不在线", Toast.LENGTH_SHORT).show();
                }
            });
        }
    };
    SeekBar.OnSeekBarChangeListener onSeekBarChangeListenerHeat = new SeekBar.OnSeekBarChangeListener() {
        int progress;
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            this.progress = progress;
            tv_heat.setText(String.valueOf(progress));
            Log.d(TAG, "onProgressChanged: 进度：" + progress + "来自用户：" +fromUser);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            AutoAdaptModel autoAdaptModel = model.getAutoAdaptModel().getValue();
            //
            String command = "heat3:"+progress;

            //在线命令
            myOneNetApi.sendCommand(command, response -> {
                if (response.body() != null && response.body().get("errno").getAsInt() == 0) {
                    Toast.makeText(getContext(), "成功创建命令", Toast.LENGTH_SHORT).show();

                    autoAdaptModel.setValue(progress, 1);
                    //更新ViewModel中的数据
                    model.setAutoAdaptModel(autoAdaptModel);
                }
                else if (response.body().get("errno").getAsInt() == 10) {
                    Toast.makeText(getContext(), "设备不在线", Toast.LENGTH_SHORT).show();
                }
            });
        }
    };

    //湿度
    View.OnClickListener onClickListenerHumid = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AutoAdaptModel autoAdaptModel = model.getAutoAdaptModel().getValue();
            boolean[] states = autoAdaptModel.getStates();
            //当前状态为开，则关闭，否则开启
            String command = "humidity2:"+(states[2]?"0":"1");

            //在线命令
            myOneNetApi.sendCommand(command, response -> {
                if (response.body() != null && response.body().get("errno").getAsInt() == 0) {
                    Toast.makeText(getContext(), "成功创建命令", Toast.LENGTH_SHORT).show();

                    //更新ViewModel中的数据
                    states[2] = !states[2];
                    autoAdaptModel.setState(states[2], 2);
                    model.setAutoAdaptModel(autoAdaptModel);
                }
                else if (response.body().get("errno").getAsInt() == 10) {
                    Toast.makeText(getContext(), "设备不在线", Toast.LENGTH_SHORT).show();
                }
            });
        }
    };
    SeekBar.OnSeekBarChangeListener onSeekBarChangeListenerHumid = new SeekBar.OnSeekBarChangeListener() {
        int progress;
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            this.progress = progress;
            tv_humid.setText(String.valueOf(progress));
            Log.d(TAG, "onProgressChanged: 进度：" + progress + "来自用户：" +fromUser);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            AutoAdaptModel autoAdaptModel = model.getAutoAdaptModel().getValue();
            //
            String command = "humidity3:"+progress;

            //在线命令
            myOneNetApi.sendCommand(command, response -> {
                if (response.body() != null && response.body().get("errno").getAsInt() == 0) {
                    Toast.makeText(getContext(), "成功创建命令", Toast.LENGTH_SHORT).show();

                    autoAdaptModel.setValue(progress, 2);
                    //更新ViewModel中的数据
                    model.setAutoAdaptModel(autoAdaptModel);
                }
                else if (response.body().get("errno").getAsInt() == 10) {
                    Toast.makeText(getContext(), "设备不在线", Toast.LENGTH_SHORT).show();
                }
            });
        }
    };

    Observer<AutoAdaptModel> autoAdaptModelObserver = new Observer<AutoAdaptModel>() {
        @Override
        public void onChanged(AutoAdaptModel autoAdaptModel) {
            boolean[] newStates = autoAdaptModel.getStates();
            int[] newValues = autoAdaptModel.getValues();
            Log.d(TAG, "ViewModel中自动调节状态改变，灯光4：" + newStates[0] + newValues[0] + "，加热：" + newStates[1] + newValues[1] + "，加湿：" + newStates[2] + newValues[2]);
            if (newStates[0]) {
                btn_light.setIconTintResource(R.color.colorPrimary);
                btn_light.setTextColor(getResources().getColor(R.color.colorPrimary));
            }
            else {
                btn_light.setIconTintResource(R.color.darker_gray);
                btn_light.setTextColor(getResources().getColor(R.color.darker_gray));
            }
            if (newStates[1]) {
                btn_heat.setIconTintResource(R.color.colorPrimary);
                btn_heat.setTextColor(getResources().getColor(R.color.colorPrimary));
            }
            else {
                btn_heat.setIconTintResource(R.color.darker_gray);
                btn_heat.setTextColor(getResources().getColor(R.color.darker_gray));
            }
            if (newStates[2]) {
                btn_humid.setIconTintResource(R.color.colorPrimary);
                btn_humid.setTextColor(getResources().getColor(R.color.colorPrimary));
            }
            else {
                btn_humid.setIconTintResource(R.color.darker_gray);
                btn_humid.setTextColor(getResources().getColor(R.color.darker_gray));
            }
            if (newStates[3]) {
                tv_state.setText("已开启");
            }
            else {
                tv_state.setText("已关闭");
            }
            sb_light.setProgress(newValues[0]);
            sb_heat.setProgress(newValues[1]);
            sb_humid.setProgress(newValues[2]);
            tv_light.setText(String.valueOf(newValues[0]));
            tv_heat.setText(String.valueOf(newValues[1]));
            tv_humid.setText(String.valueOf(newValues[2]));
        }
    };
}